<template>
	<view class="p-30">
		<u--form labelPosition="left" :model="formData" ref="uForm" labelWidth="100">
			<view class="box">
				<u-form-item label="送检时间" prop="testDate" :required="true">
					<view class="flex justify-between w-100" :class="[formData.testDate?'':'color-C7C7CC']"
						@click="dateHandler('testDate')">
						<view>{{formData.testDate||'请选择设备送检时间'}}</view>
						<u-icon name="arrow-down-fill" color="#C7C7CC"></u-icon>
					</view>
				</u-form-item>
				<u-line :color="lineColor"></u-line>
				<u-form-item label="取回时间" prop="backDate" :required="formRequired">
					<view class="flex justify-between w-100" :class="[formData.backDate?'':'color-C7C7CC']"
						@click="formData.id&&dateHandler('backDate')">
						<view>{{formData.backDate||'请选择设备取回时间'}}</view>
						<u-icon name="arrow-down-fill" color="#C7C7CC"></u-icon>
					</view>
				</u-form-item>
			</view>
			<view class="box">
				<u-form-item label="检测报告" prop="num" :required="formRequired">
					<u--input placeholder="请输入检测报告编号" border="none" v-model="formData.num"></u--input>
				</u-form-item>
				<u-line :color="lineColor"></u-line>
				<u-form-item label="检测结论" prop="conclusion" :required="formRequired" labelPosition="top">
					<u--textarea class="m-t-20" v-model="formData.conclusion" placeholder="请输入内容" :confirmType="null"
						:showConfirmBar='false'></u--textarea>
				</u-form-item>
				<u-line :color="lineColor"></u-line>
				<u-form-item label="报告图片" prop="testFiles" :required="formRequired" labelPosition="top">
					<u-upload class="m-t-20" :fileList="formData.testFiles" name="img" multiple :maxCount="10"
						:previewFullImage="true" @afterRead="afterRead" @delete="deletePic"></u-upload>
				</u-form-item>
			</view>
		</u--form>
		<u-datetime-picker ref="picker" :show="show" mode="datetime" @confirm="onConfirm"
			@cancel="onCancel"></u-datetime-picker>
		<view class="window-bottom">
			<u-button type="primary" text="提交" @click="onSubmit"></u-button>
		</view>
		<u-modal :show="modalShow" :content="content" :showCancelButton="true" @cancel="modalShow=false;"
			@confirm="onDeleteConfirm"></u-modal>
	</view>
</template>

<script>
	import {
		baseUrl
	} from '@/request/request.js'
	export default {
		data() {
			return {
				show: false,
				modalShow: false,
				content: '确认要删除该图片？删除后将无法恢复！',
				lineColor: '#F2F2F2',
				timeKey: 'testDate',
				formData: {
					instrumentsId: '',
					backDate: '',
					conclusion: '',
					testDate: new Date().Format('yyyy-MM-dd hh:mm:ss'),
					num: '',
					testFiles: [],
					testFileIds: [],
				},
				deleteEvent: {},
				rules: {
					'testDate': {
						type: 'string',
						required: true,
						message: '请选择送检时间',
						trigger: ['blur', 'change']
					},
				},
				allRules: {
					'testDate': {
						type: 'string',
						required: true,
						message: '请选择送检时间',
						trigger: ['blur', 'change']
					},
					'backDate': {
						type: 'string',
						required: true,
						message: '请选择取回时间',
						trigger: ['blur', 'change']
					},
					'num': {
						type: 'string',
						required: true,
						message: '请输入检测报告编号',
						trigger: ['blur', 'change']
					},
					'conclusion': {
						type: 'string',
						required: true,
						message: '请输入检测结论',
						trigger: ['blur', 'change']
					},
					'testFiles': {
						type: 'array',
						required: true,
						message: '请上传报告图片',
						trigger: ['blur', 'change']
					},
				}
			}
		},
		onLoad(option) {
			this.formData.instrumentsId = option.instrumentsId
			this.formData.id = option.checkId
			this.type = option.code
			if (option.checkId) {
				this.getDetail()
			}
		},
		onReady() {
			let rules = {}
			if (this.type == 'getOmList') {
				rules = this.rules
			} else {
				rules = this.allRules
			}
			this.$refs.picker.innerValue = this.formData.testDate
			this.$refs.uForm.setRules(rules)
		},
		computed: {
			formRequired() {
				if (this.type == 'getOmList') return false
				return true
			}
		},
		methods: {
			getDetail() {
				this.$api.getTestDetail({
					id: this.formData.id
				}).then(res => {
					this.formData = res.data
					this.formData.backDate = this.formData.backDate || new Date().Format('yyyy-MM-dd hh:mm:ss')
					this.$refs.picker.innerValue = this.formData.backDate
					this.formData.testFileIds = res.data.testFiles.map(item => {
						item.url = baseUrl + '/' + item.uploadName
						return item.fileId
					})
				})
			},
			dateHandler(key) {
				this.timeKey = key
				this.$refs.picker.innerValue = this.formData[key]
				this.show = true
			},
			onConfirm(val) {
				this.formData[this.timeKey] = new Date(val.value).Format('yyyy-MM-dd hh:mm:ss')
				this.onCancel()
			},
			onCancel() {
				this.show = false
			},
			// 删除图片二次确认框
			deletePic(event) {
				this.modalShow = true
				this.deleteEvent = event
			},
			// 删除图片 如果是服务器端的图片择调用删除接口
			async onDeleteConfirm() {
				if (this.deleteEvent.file.fileId) {
					await this.$api.deletupload([this.deleteEvent.file.fileId])
				}
				this.formData.testFiles.splice(this.deleteEvent.index, 1)
				this.modalShow = false
			},
			onSubmit() {
				let apiName = 'submitTest'
				if (this.formData.id) {
					apiName = 'editTest'
				}
				this.$refs.uForm.validate().then(res => {
					this.$api[apiName](this.formData).then(res => {
						let id = this.formData.id
						if (res.data) {
							id = res.data.id
						}
						this.uploadFilePromise(id)
					})
				}).catch(errors => {})
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.formData.testFiles.length
				lists.map((item) => {
					this.formData.testFiles.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					let item = this.formData.testFiles[fileListLen]
					this.formData.testFiles.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
					}))
					fileListLen++
				}
			},
			uploadFilePromise(id) {
				let params = {
					'relatedId': id,
					'rt': 'test',
				}
				let promiseList = []
				promiseList = this.formData.testFiles.filter(item => !item.fileId).map(item => this.$api.addupload(params,
					item))
				Promise.all(promiseList).then(res => {
					uni.showToast({
						title: '添加成功',
					})
					uni.navigateBack()
					// uni.navigateTo({
					// 	url: '/pages/check/check'
					// })
				}).catch(e => {
					uni.showToast({
						title: '图片上传失败',
					})
					this.getDetail()
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.box {
		background-color: #fff;
		padding: 10rpx 30rpx;
		box-shadow: 0rpx 2rpx 15rpx 1rpx rgba(173, 173, 173, 0.1);
		border-radius: 10rpx;
		margin-bottom: 20rpx;
	}
</style>